/**
 * User: 蕨菜
 * Date: 2019-05-15
 * Time: 11:48
 * Description: 此文件简要说明
 */

const Router = require('koa-router');
const sequelize = require('sequelize');
const querystring = require('querystring');

const classRouter = new Router();

const { AppUtil } = require('../util');
const {
    addToModel,
    updateModelById,
    associationModel,
    getAll,
    getDataByIdList,
    deleteById,
    deleteByIdWithAssociationModel,
} = require('../helper');

const validates = [{
    key: 'name',
    type: 'string',
}, {
    key: 'active',
    type: 'boolean'
}];

const {
    Teacher,
    Class,
    Grade,
} = require('../models');

const {
    addClass,
    deleteClass,
    updateClass,
    getClass
} = require('../actions/class')

classRouter.get('/test', async function (ctx) {
    const data = await getDataByIdList(Teacher, [1, 2, 3])
    ctx.body = {
        data
    }
})

classRouter.post('/updateClass', async (ctx) => {
    const body = ctx.request.body || {};
    const { isValid, message } = AppUtil.validateParams(validates, body);

    if (!isValid) {
        ctx.body = message;
        return;
    }

    if (AppUtil.isEmpty(body.id)) {
        return await addClass(body, ctx);
    }
    return await updateClass(body, ctx);

})

classRouter.post('/deleteClass', async (ctx) => {
    const body = ctx.request.body || {};
    if (AppUtil.isEmpty(body.id)) {
        return ctx.body = AppUtil.requestFailed('id不能为空');
    }

    const classInstance = await Class.findByPk(body.id);

    await deleteByIdWithAssociationModel('setTeachers', classInstance);
    const data = await deleteById(Class, body.id);
    return ctx.body = {
        success: true,
        data
    }

})

classRouter.post('/getClass', async (ctx) => {
    const body = ctx.request.body || {};

    const { teacherId, name, startTime, endTime, ...othersQuery } = body;
    const teacherWhere = AppUtil.isEmpty(teacherId) ? {} : {
        id: teacherId,
    }
    const where = { ...othersQuery };

    if (!AppUtil.isEmpty(name)) {
        where.name = {
            [sequelize.Op.like]: `%${name}%`
        }
    }

    const { isValid, timeData } = AppUtil.getStartAndEndTime(startTime, endTime);

    if (!isValid) {
        return ctx.body = AppUtil.requestFailed('开始时间不能大于结束时间');
    }

    if (!AppUtil.isEmpty(timeData)) {
        where.createAt = {
            [sequelize.Op.gt]: timeData[0],
            [sequelize.Op.lt]: timeData[1],
        }
    }

    const data = await getAll(Class, {
        where,
        include: [{
            model: Teacher,
            where: teacherWhere,
            through: {
                attributes: []
            }
        }]
    })
    return ctx.body = {
        success: true,
        data
    };

})

module.exports = classRouter;